<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #box p {
        height: 300px;
        font-size: 3rem;
        display: flex;
        justify-content: center;
        align-items: center;
        border: solid;
      }

      #top {
        width: 100px;
        height: 100px;
        font-size: 2rem;
        background-color: rgb(132, 132, 1);
        color: white;
        position: fixed;
        bottom: 60px;
        right: 60px;
        display: none;
        justify-content: center;
        align-items: center;
        cursor: pointer;
      }
      #top:hover {
        background-color: rgb(80, 80, 3);
      }
    </style>
  </head>
  <body>
    <div id="box">
      <p>p1</p>
      <p>p2</p>
      <p>p3</p>
      <p>p4</p>
      <p>p5</p>
      <p>p6</p>
    </div>

    <div id="top">TOP</div>
    <script>
      const topBox = document.getElementById("top");
      topBox.onclick = function () {
        window.scrollTo({
          top: 0,
          left: 0,
          behavior: "smooth",
        });
      };
      window.onscroll = function (e) {
        const h1 = document.documentElement.scrollHeight;
        const h2 = window.pageYOffset;
        const h3 = window.innerHeight;
        // 判断触底
        if (h1 - h2 - h3 < 60) {
          // 添加新内容
          const p = document.createElement("p");
          p.innerHTML = "new P";
          box.append(p);
        }
        // 当滚出去的文档高度pageYOffset，超过一屏innerHeight的时候，出现topBox
        if (h2 - h3 > 10) {
          topBox.style.display = "flex";
        } else {
          topBox.style.display = "";
        }
      };
    </script>
  </body>
</html>
